package com.onefish.toolkit;

import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;

public class RefreshAndRestartListener implements ApplicationListener<RefreshAndRestartEvent> {
    private final ConfigurableApplicationContext context;

    public RefreshAndRestartListener(ConfigurableApplicationContext context) {
        this.context = context;
    }

    @Override
    public void onApplicationEvent(RefreshAndRestartEvent event) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Restarting the application...");
                context.close();
                SpringApplication.run(Application.class);
            }
        });
        thread.setDaemon(false);
        thread.start();
    }
    public static void addApplicationListener(ConfigurableApplicationContext context){
        // 注册事件监听器
		context.addApplicationListener(new RefreshAndRestartListener(context));
    }
    public static void publishEvent(){
        //  发布事件触发执行
        Application.context.publishEvent(new RefreshAndRestartEvent(Application.context));
    }
}
